/**
 * 
 */
package com.geekteam.masterenglish.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Base64;
import android.widget.Toast;

import com.geekteam.masterenglish.R;
import com.geekteam.masterenglish.provider.EEDatabase;
import com.geekteam.masterenglish.utils.Constants.SharePreference;

/**
 * @author MTROL
 * 
 */
public class Utils {
	
	public static final long SECOND_MILLIS = 1000;
	public static final long MINUTE_MILLIS = 60 * SECOND_MILLIS;
	public static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
	public static final long DAY_MILLIS = 24 * HOUR_MILLIS;
	private static StringBuilder mBuilder = new StringBuilder();
	
	public static String base64(String json) {
		String result = null;
		byte[] encoded = Base64.encode(json.getBytes(), Base64.URL_SAFE);
		result = new String(encoded);
		result = result.replaceAll("=", "%3D");
		result = result.replaceAll("[\\t\\n\\r]", "");
		return result;
	}

	public static String hmacMD5(String msg, String keyString, String algo) {
		String digest = null;
		try {
			SecretKeySpec key = new SecretKeySpec(
					(keyString).getBytes("UTF-8"), algo);
			Mac mac = Mac.getInstance(algo);
			mac.init(key);

			byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));

			StringBuffer hash = new StringBuffer();
			for (int i = 0; i < bytes.length; i++) {
				String hex = Integer.toHexString(0xFF & bytes[i]);
				if (hex.length() == 1) {
					hash.append('0');
				}
				hash.append(hex);
			}
			digest = hash.toString();
		} catch (UnsupportedEncodingException e) {
		} catch (InvalidKeyException e) {
		} catch (NoSuchAlgorithmException e) {
		}
		return digest;
	}

	public static boolean hasFroyo() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
	}

	public static boolean hasGingerbread() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}

	public static boolean hasHoneycombMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
	}

	public static boolean hasICS() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
	}

	public static boolean hasJellyBean() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
	}

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public static boolean isHoneycombTablet(Context context) {
		return hasHoneycomb() && isTablet(context);
	}
	
	public static boolean isDataBaseEmpty(Context context){
		SQLiteOpenHelper dbHelper = new EEDatabase(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT * FROM "+EEDatabase.Tables.LESSIONS, null);
		boolean result = cursor.getCount() == 0;
		cursor.close();
		db.close();
		return result;
	}
	
	private static HashMap<String, String> mAlbumBookMap;
	
	public static String getBookId(String albumId){
		if(mAlbumBookMap==null){
			initAlbumBookMap();
		}
		
		if(mAlbumBookMap.containsKey(albumId)){
			return mAlbumBookMap.get(albumId);
		}
		
		return "";
	}
	
	private static void initAlbumBookMap(){
		mAlbumBookMap = new HashMap<String, String>();
		String listeningPracticeThroughDictation = EEApplications.getInstance().getString(R.string.bookId_1);
		mAlbumBookMap.put("IWED0CBF", listeningPracticeThroughDictation);
		mAlbumBookMap.put("IWEE076I", listeningPracticeThroughDictation);
	}
	
	public static void updateFirstTimeUse(Context context, boolean isFirtTime){
		SharedPreferences share = context.getSharedPreferences(SharePreference.MAIN_KEY, Activity.MODE_PRIVATE);
		Editor editor = share.edit();
		editor.putBoolean(SharePreference.IS_FIRST_TIME, isFirtTime);
		editor.commit();
	}
	
	public static boolean isFirstTimeUse(Context context){
		SharedPreferences share = context.getSharedPreferences(SharePreference.MAIN_KEY, Activity.MODE_PRIVATE);
		return share.getBoolean(SharePreference.IS_FIRST_TIME, true);
	}
	
	public static boolean isUpdate(long lastUpdate){
		long currentTime = System.currentTimeMillis();
		return (currentTime - lastUpdate) > 30 * MINUTE_MILLIS;
	}
	
	/**
	 * Function to convert milliseconds time to
	 * Timer Format
	 * Hours:Minutes:Seconds
	 * */
	public static String milliSecondsToTimer(long milliseconds){
		int minutes = (int) (milliseconds / MINUTE_MILLIS);
		int seconds = (int) ((milliseconds % MINUTE_MILLIS) / 1000);

		if (minutes < 10) {
			mBuilder.append(0).append(minutes);
		} else {
			mBuilder.append(minutes);
		}

		if (seconds < 10) {
			mBuilder.append(":0").append(seconds);
		} else {
			mBuilder.append(":").append(seconds);
		}

		String finalTimerString = mBuilder.toString();
		mBuilder.delete(0, mBuilder.length());

		// return timer string
		return finalTimerString;
	}
	
	/**
	 * Function to get Progress percentage
	 * @param currentDuration
	 * @param totalDuration
	 * */
	public static int getProgressPercentage(long currentDuration, long totalDuration){
		Double percentage = (double) 0;
		
		long currentSeconds = (int) (currentDuration / 1000);
		long totalSeconds = (int) (totalDuration / 1000);
		
		// calculating percentage
		percentage =(((double)currentSeconds)/totalSeconds)*100;
		
		// return percentage
		return percentage.intValue();
	}

	/**
	 * Function to change progress to timer
	 * @param progress - 
	 * @param totalDuration
	 * returns current duration in milliseconds
	 * */
	public static int progressToTimer(int progress, int totalDuration) {
		int currentDuration = 0;
		totalDuration = (int) (totalDuration / 1000);
		currentDuration = (int) ((((double)progress) / 100) * totalDuration);
		
		// return current duration in milliseconds
		return currentDuration * 1000;
	}
	
	public static void downloadFile(Context context, String url, String title) throws IOException{
		InputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
	        File file = new File(context.getExternalFilesDir(context.getResources().getString(R.string.folder_cache)), title);
	        if(file.exists()){
	        	return;
	        }
	        
	        url = url.replaceAll(" ", "%20");
	        URLConnection urlConnect = (new URL(url)).openConnection();
	        
			urlConnect.connect();   
	        inputStream = new BufferedInputStream(urlConnect.getInputStream());
	        outputStream = new FileOutputStream(file);   
	        
	        byte data[] = new byte[1024];
            int count;
            while ((count = inputStream.read(data))!= -1) {
                outputStream.write(data, 0, count);
            }            
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(outputStream!=null && inputStream!=null){
				outputStream.flush();
		       	outputStream.close();
		        inputStream.close();
			}
		}
	}
	
	public static void downloadFile(Context context, String url, String title, String book) throws IOException{
		InputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			String state = Environment.getExternalStorageState();
			
			 if (!Environment.MEDIA_MOUNTED.equals(state)){
				 showToastFromService(context, R.string.make_dir_error);
				 return;
			 }
			
	        File folder = new File(Environment.getExternalStorageDirectory(), String.format(context.getString(R.string.folder_download), book));
	        if(!folder.exists()){
	        	if(!folder.mkdirs()){
	        		showToastFromService(context, R.string.make_dir_error);
	        		return;
	        	}
	        }
	        
	        File file = new File(folder, title+".mp3");
	        if(file.exists()){
	        	showToastFromService(context, R.string.download_complete);
	        	return;
	        }
	        
	        url = url.replaceAll(" ", "%20");
	        URLConnection urlConnect = (new URL(url)).openConnection();
	        
			urlConnect.connect();   
	        inputStream = new BufferedInputStream(urlConnect.getInputStream());
	        outputStream = new FileOutputStream(file);   
	        
	        byte data[] = new byte[1024];
            int count;
            while ((count = inputStream.read(data))!= -1) {
                outputStream.write(data, 0, count);
            }            
		} catch (MalformedURLException e) {
			e.printStackTrace();
			showToastFromService(context, R.string.download_error);
		} catch (IOException e) {
			e.printStackTrace();
			showToastFromService(context, R.string.download_error);
		}finally{
			if(outputStream!=null && inputStream!=null){
				outputStream.flush();
		       	outputStream.close();
		        inputStream.close();
			}
		}
		
		showToastFromService(context, R.string.download_complete);
	}
	
	public static void showToastFromService(final Context context,
			final int resId) {
		showToastFromService(context, context.getResources().getString(resId));
	}
	
	public static void showToastFromService(final Context context,
			final String content) {
		Thread toastThread = new Thread() {
			public void run() {
				Looper.prepare();
				Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		};
		toastThread.start();
	}
}
